package com.cy.teducommunitys.com.cy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cy.teducommunitys.com.common.annotation.RequiredLog;
import com.cy.teducommunitys.com.common.vo.RoleMenuVo;
import com.cy.teducommunitys.com.cy.entity.Authority;
import com.cy.teducommunitys.com.cy.entity.Role;
import com.cy.teducommunitys.com.cy.mapper.AuthorityMapper;
import com.cy.teducommunitys.com.cy.mapper.RoleMapper;
import com.cy.teducommunitys.com.cy.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author mdzz
 * @since 2019-07-19
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    private RoleMapper mapper;
    @Autowired
    private AuthorityMapper authMapper;

    @Autowired
    public RoleServiceImpl(RoleMapper mapper) {
        super(mapper);
        this.mapper = mapper;
    }
    @RequiredLog("保存角色")
    public int saveObject(Role entity, Integer[] menuIds) {
        //验证参数
        if(entity == null)
            throw new IllegalArgumentException("角色不能为空");
        if("".equals(entity.getName()))
            throw new IllegalArgumentException("名称不能为空");
        if(menuIds==null || menuIds.length==0)
            throw new IllegalArgumentException("菜单权限不能为空");

        int rows = 0;
        Integer orgId = entity.getRoleId(); //id是空则是新增，否则修改
        rows = super.saveObject(entity, orgId);
        //新增角色关系
        if(orgId == null || orgId<=0)
        {
            Integer roleId = entity.getRoleId();
            authMapper.insertObject(roleId,menuIds,entity.getCreatedUser());
        }
        else{ //修改角色关系
            authMapper.deleteObject(orgId);
            authMapper.insertObject(orgId,menuIds,entity.getCreatedUser());
        }
        return rows;
    }

    @RequiredLog("删除")
    @Override
    public void deleteRoleById(Integer id) {
        if(id==null || id<0)
            throw new IllegalArgumentException("无效id");
        authMapper.deleteObject(id);
        mapper.deleteById(id);
    }

    @RequiredLog("查询")
    @Override
    public RoleMenuVo findObjectByRoleId(Integer id) {
        RoleMenuVo roleMenuVo = mapper.findObjectByRoleId(id);
        return roleMenuVo;
    }


}
